from models import *




def add(req):
    try: 
        name = req['name']
        category = req['category']
        describtion = req['describtion']
        status = req['status']
        dev = DeviceModel(name=name)
        dev.category = category
        dev.describtion = describtion
        dev.modifiedtime = datetime.datetime.now()
        dev.status = status
        dev.save()
        return True
    except:
        return False

def getone(rid):
    try:
        dev = DeviceModel.objects(id=rid)
        if dev.count():
            return dev[0].to_json()
        else:
            return None
    except:
        return False
    
def getAll():
    try:
        dev =DeviceModel.objects
        if dev.count():
            return dev.to_json()
        else:
            return None
    except:
        return False
    
def deleteone(rid):
    try:
        dev = DeviceModel.objects(id=rid)
        if dev.count():
            dev.delete()
            return True
        else:
            return False
    except:
        return False
    
def update(req):
    try:
        devs = DeviceModel.objects(id=req['id'])
        if devs.count():
            dev = devs[0]
            dev.name = req['name']
            dev.category = req['category']
            dev.describtion = req['describtion']
            dev.status = req['status']
            dev.modifiedtime = datetime.datetime.now()
            thislist = []
            thatlist = []
            dev.nickname = req['nickname']
            try:
                getthis = req['thislist']
                if getthis:
                    for t in getthis:
                        this = ThisService(serviceType=t['serviceType'])
                        this.serviceName = t['serviceName']
                        this.ThisTpye = t['ThisTpye']
                        this.Threshold = t['Threshold']
                        thislist.append(this)
                dev.thislist = thislist
            except:
                print " "
            try:
                getthat = req['thatlist']
                if getthat:
                
                    for t in getthat:
                        that = ThatService(serviceType=t['serviceType'])
                        that.serviceName = t['serviceName']
                        that.ActionTpye = t['ActionTpye']
                        that.Action = t['Action']
                        thatlist.append(that)
                dev.thatlist = thatlist
            except:
                print ' '
            dev.save()
            return True
            
    except:
        return False

def changenickname(rid,nickname):
    try:
        dev = DeviceModel.objects(id=rid)[0]
        if dev.count():
            dev.nickname = nickname
            dev.save()
            return True
        else:
            return None
    except:
        return False

